package org.act.xservices.rt.xcontainer.deployment.util;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;

import org.act.xservices.rt.xcontainer.deployment.DeploymentException;

public class DeployUtil {

	/**
	 * Get a ClassLoader which contains a classpath of a) the passed directory
	 * and b) any jar files inside the "lib/" or "Lib/" subdirectory of the
	 * passed directory.
	 * 
	 * @param parent
	 *            parent ClassLoader which will be the parent of the result of
	 *            this method
	 * @param file
	 *            a File which must be a directory for this to be useful
	 * @return a new ClassLoader pointing to both the passed dir and jar files
	 *         under lib/
	 * @throws DeploymentException
	 *             if problems occur
	 */
	public static ClassLoader getClassLoader(final ClassLoader parent, File file)
			throws DeploymentException {
		
		URLClassLoader classLoader;

		if (file == null)
			return parent;

		try {
			ArrayList<URL> urls = new ArrayList<URL>();
			urls.add(file.toURL());

			// lower case directory name
			File libfiles = new File(file, "lib");
			if (!addFiles(urls, libfiles)) {
				// upper case directory name
				libfiles = new File(file, "Lib");
				addFiles(urls, libfiles);
			}

			final URL[] urllist = urls.toArray(new URL[0]);
			
			classLoader = new URLClassLoader(urllist, parent);
			
			return classLoader;
		} catch (MalformedURLException e) {
			throw new DeploymentException(e);
		}
	}

	
	private static boolean addFiles(ArrayList<URL> urls, 
			final File libfiles) throws MalformedURLException {
		
		if (libfiles.exists()) {
			urls.add(libfiles.toURL());
			File jarfiles[] = libfiles.listFiles();
			
			for (int i = 0; i < jarfiles.length; i++) {
				File jarfile = jarfiles[i];
				if (jarfile.getName().endsWith(".jar")) {
					urls.add(jarfile.toURL());
				}
			}
			return true;
		}
		return false;
	}
	
	
    public static String getFileExtension(String fileName) {
        int index = fileName.lastIndexOf('.');
        return fileName.substring(index + 1);
    }
    
    /**
     *
     * @param fileName the archive file name
     * @return Returns String.
     */
    public static String getFileNameWithoutExtension(String fileName) {
        char seperator = '.';
        String value;
        int index = fileName.lastIndexOf(seperator);
        if (index > 0) {
            value = fileName.substring(0, index);
            return value;
        }
        return fileName;
    }

}
